package site.wanjiahao.set;

import site.wanjiahao.tree.BinaryTree;
import site.wanjiahao.tree.RBTree;

/**
 * 使用红黑树，构造集合，但是需要注意的是，元素必须具有可比较性
 * @param <E>
 */
public class TreeSet<E> implements Set<E>{

    private final RBTree<E> tree = new RBTree<>();

    @Override
    public int size() {
        return tree.size();
    }

    @Override
    public boolean isEmpty() {
        return tree.isEmpty();
    }

    @Override
    public void clear() {
        tree.clear();
    }

    @Override
    public boolean contains(E ele) {
        return tree.contains(ele);
    }

    @Override
    public void add(E ele) {
        // 直接添加，元素已经除去重复
        tree.add(ele);
    }

    @Override
    public void remove(E ele) {
        tree.remove(ele);
    }

    @Override
    public void traversal(Consumer<E> consumer) {
        tree.inorderTraversal(new BinaryTree.Consumer<E>() {
            @Override
            public boolean accept(E e) {
                return consumer.visit(e);
            }
        });
    }
}
